<template>
  <div class="map">
    <div id="map" :style="{ height: maxHeight }"></div>
    <div
      class="refresh-station-box cursor-pointer"
      @click="handleRefreshStation"
    >
      <i class="el-icon-refresh-left" size="16"></i>
    </div>

    <!-- 弹窗显示当前站点所有线路信息 -->
    <route-list
      :collectDatas="collectDatas"
      :routeName="routeName"
      :isCloseBtn="true"
      :isBackBtn="true"
      @handleChangeRoute="handleChangeRoute"
      @handleClose="handleClose"
      v-if="isShowRouteList && isCollecData"
    />
    <div
      style="position: fixed; bottom: 0; right: 0; z-index: 999"
      @click="handleRestore"
    >
      <img src="@/assets/images/shuaxin.png" alt="" />
    </div>
    <!-- 公告 -->
    <!-- <div class="notice">
      <notification/>
    </div> -->
  </div>
</template>
<script>
import { Map, View, Feature } from "ol";
import { Point } from "ol/geom";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import { Stroke, Icon, Style, Fill, Text } from "ol/style";
import { getAllSite } from "@/api/collect";
import "ol/ol.css";
import { getStationRoute, getMessageinfos, getPredict } from "@/api/collect";
import routeList from "@/components/routeList";
import notification from "@/components/notification";
import googleMapLine from "@/utils/maps/googleMap";
import { mapState } from "vuex";
import { Notification } from "element-ui";
import { getRefreshTime } from "@/utils/location";
export default {
  components: {
    routeList,
    notification,
  },
  data() {
    return {
      // 服务器下发数据的话，需要进行watch监听
      collectDatas: [], //线路列表
      isShowRouteList: false, //是否显示线路弹窗
      routeName: "", //车站名称
      routeRundirection: "", //线路运行方向
      maxHeight: "", //可视区高度
      isCollecData: false,
      dualserialid: "",
      inputBusroute: "",
      setTime: null,
      refreshTime: null,
      getPredictList: [],
    };
  },
  computed: {
    ...mapState(["lnglat", "changeRefresh", "changeWebsite"]),
  },
  watch: {
    lnglat() {
      this.handleRestore();
    },
    changeRefresh() {
      this.getRefreshTime();
      this.getStationRoute();
    },
    changeWebsite() {},
  },
  created() {
    this.getMessageinfos();
  },

  mounted() {
    let maxHeight =
      window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight;
    this.maxHeight = maxHeight + "px";

    // 获取所有站点

    this.getAllSite();
    this.refreshTime = getRefreshTime(this.$store.state.changeRefresh);
  },
  methods: {
    // 获取通告信息

    async getMessageinfos() {
      let that = this;
      let date = this.$dayjs(new Date().getTime()).format(
        "YYYY-MM-DD hh:mm:ss"
      );
      let params = {
        time: date,
        type: '1'
      };
      let { status, data } = await getMessageinfos(params);
      if (status == 200) {
        let message = "";

        data.forEach((item) => {
          message = message + "\n" + item.content;
        });
        // message=data[0].content
        const h = this.$createElement;
        this.$notify({
          title: this.$t("langName.langName104"),
          message: h(
            "button",
            {
              style:
                "height:300px;background:#fff;overflow:auto;border:1px solid #fff;",
              class: "notify-success",
            },
            message
          ),
          position: "bottom-right",
          duration: 0,
          dangerouslyUseHTMLString: true,
        });
      }
    },
    // 获取全部站点
    async getAllSite() {
      //  this.initMap();
      if (sessionStorage.getItem("allStationLists")) {
        this.siteLists = JSON.parse(sessionStorage.getItem("allStationLists"));
      } else {
        let { status, data } = await getAllSite();
        if (status == 200) {
          this.siteLists = data;
          sessionStorage.setItem(
            "allStationLists",
            JSON.stringify(this.siteLists)
          );
        }
      }

      this.initMap();
      let now = setInterval(async () => {
        let { status, data } = await getAllSite();
        if (status == 200) {
          this.siteLists = data;
          sessionStorage.setItem(
            "allStationLists",
            JSON.stringify(this.siteLists)
          );
        }
      }, 1000 * 60 * 60 * 24);
    },
    // 刷新全部站点
    async handleRefreshStation() {
      let { status, data } = await getAllSite();
      if (status == 200) {
        this.siteLists = data;
        sessionStorage.setItem(
          "allStationLists",
          JSON.stringify(this.siteLists)
        );
      }
    },
        // 复原地图
    handleRestore() {
      if (this.map) {
        this.map.getView().animate({
          center: this.$store.state.lnglat,
          // center: [120.14727,35.984278],
          zoom: window.MAPSETTINGS.DEFAULTZOOM,
        });
      }
    },
    // 绘制地图
    initMap() {
      let that = this;
      this.map = new Map({
        target: "map",
        layers: [googleMapLine.initMapLayer()],
        view: new View({
          projection: "EPSG:4326",
        }),
      });
      this.handleRestore();

      this.drawSpot();
      this.map.on("click", function (evt) {
        let pixel = that.map.getEventPixel(evt.originalEvent);
        let feature = that.map.forEachFeatureAtPixel(pixel, function (feature) {
          return feature;
        });
        if (feature) {
          that.isShowRouteList = true;
          that.routeName = feature.values_.stationName;
          that.routeRundirection = feature.values_.rundirection;
          that.dualserialid = feature.values_.dualserialid;
          that.stationid = feature.values_.stationid;
          that.segmentid = feature.values_.segmentid;
          that.getStationRoute();
        }
      });

    },
    

    // 绘制站点
    drawSpot() {
      if (!this.siteLists) return;
      let that = this;
      let pointFeature = null;
      // 绘制中心点
      let pointFeatureCenter = new Feature({
        type: "icon",
        geometry: new Point(this.$store.state.lnglat),
      });
      let pointSourceCenter = new VectorSource({
        features: [pointFeatureCenter],
      });
      let pointLayer1 = new VectorLayer({
        source: pointSourceCenter, //数据源
        style: new Style({
          image: new Icon({
            anchorOrigin: "bottom-right",
            src: require("@/assets/images/mapAddress.png"),
          }),
        }),
      });
      this.map.addLayer(pointLayer1);
      // 绘制车站
      this.siteLists.forEach((v) => {
        pointFeature = new Feature({
          type: "icon",
          geometry: new Point([v.longitude, v.latitude]),
        });
        pointFeature.set("stationName", v.stationname);
        pointFeature.set("rundirection", v.rundirection);
        pointFeature.set("dualserialid", v.dualserialid);
        pointFeature.set("stationid", v.stationid);
        pointFeature.set("segmentid", v.segmentid);

        let pointSource = new VectorSource({
          features: [pointFeature],
        });

        let pointLayer = new VectorLayer({
          //绘制图层
          source: pointSource, //数据源
          style: new Style({
            image: new Icon({
              anchorOrigin: "bottom-right",
              src: require("@/assets/images/busStop.png"),
              anchor: [1, 1], //设置图标偏移
                  scale:0.5
            }),
            text: new Text({
              textAlign: "center", //对齐方式
              textBaseline: "middle", //文本基线
              font: "normal 12px 微软雅黑", //字体样式
              text: v.stationname, //文本内容 v.stationname
              borderRadius: "10px",
              offsetY: 40, // Y轴偏置
              fill: new Fill({
                //填充样式
                color: "#000",
              }),
              // ffcc33
              backgroundStroke: new Stroke({ color: "#f78989", width: 1 }),
              backgroundFill: new Fill({
                // 填充背景
                color: "rgb(255,255,255)",
              }),
              padding: [2, 5, 2, 5],
            }),
          }),
        });
        this.map.addLayer(pointLayer);
      });
    },

    async getPredict() {
      let params = {
        stationId: this.stationid,
        segmentid: this.segmentid,
      };
      let { status, data } = await getPredict(params);
      if (status == 200) {
        return data;
      }
    },
    // 获取选中站点的所有线路
    async getStationRoute() {
      clearInterval(this.setTime);
      let params = {
        stationId: this.stationid,
        userId: localStorage.getItem("userId")
          ? localStorage.getItem("userId")
          : "", //用户id
      };
      let { status, data } = await getStationRoute(params);
      if (status == 200) {
        this.getPredict().then((res) => {
          this.getPredictList = res;
          this.collectDatas = data;
          this.isCollecData = true;
          this.collectDatas.forEach((item) => {
            this.getPredictList.forEach((i) => {
              if (item.routeid == i.routeId) {
                item.firstBusState = i.firstBusState; //第一辆车状态  1正常预测；2不能预测；3无车可预测
                item.firstBusStationSum = i.firstBusStationSum; //第一辆车距当前站数
                item.firstBusPtime = i.firstBusPtime; //第一辆预测时间
                item.secondBusState = i.secondBusState; //第一辆车状态  1正常预测；2不能预测；3无车可预测
                item.secondBusStationSum = i.secondBusStationSum; //第一辆车距当前站数
                item.secondBusPtime = i.secondBusPtime; //第一辆预测时间

                item.ifHavePredictBus = i.ifHavePredictBus; //是否有预测车辆
                item.nextSendTime = i.nextSendTime; //下一辆车发车时间

                item.predictState = i.predictState; //预测总体状态
                item.firstBusDesc = i.firstBusDesc; //预测总体情况描述
              }
            });
          });
        });
      }
      this.setTime = setInterval(async () => {
        let { status, data } = await getStationRoute(params);
        if (status == 200) {
          this.getPredict().then((res) => {
            this.getPredictList = res;
            this.collectDatas = data;
            this.isCollecData = true;
            this.collectDatas.forEach((item) => {
              this.getPredictList.forEach((i) => {
                if (item.routeid == i.routeId) {
                  item.firstBusState = i.firstBusState; //第一辆车状态  1正常预测；2不能预测；3无车可预测
                  item.firstBusStationSum = i.firstBusStationSum; //第一辆车距当前站数
                  item.firstBusPtime = i.firstBusPtime; //第一辆预测时间
                  item.secondBusState = i.secondBusState; //第一辆车状态  1正常预测；2不能预测；3无车可预测
                  item.secondBusStationSum = i.secondBusStationSum; //第一辆车距当前站数
                  item.secondBusPtime = i.secondBusPtime; //第一辆预测时间

                  item.ifHavePredictBus = i.ifHavePredictBus; //是否有预测车辆
                  item.nextSendTime = i.nextSendTime; //下一辆车发车时间

                  item.predictState = i.predictState; //预测总体状态
                  item.firstBusDesc = i.firstBusDesc; //预测总体情况描述
                }
              });
            });
          });
        }
      }, this.refreshTime);
    },
    // 关闭线路弹窗
    handleClose() {
      this.isShowRouteList = false;
      clearInterval(this.setTime);
    },
    // 点击弹窗线路信息-进入线路详情
    handleChangeRoute(item, index) {
      this.$store.commit("setRouteListStore", item);
      this.$router.push({
        name: "routeDetail",
        params: {
          routeName: this.routeName,
          stationid: this.stationid,
          index: index,
        },
      });
    },
  },
  destroyed() {
    clearInterval(this.setTime);
    Notification.closeAll();
  },
};
</script>
<style>
.notify-success::-webkit-scrollbar {
  width: 0px;
}
</style>
<style lang="scss" scoped>
.map {
  overflow: hidden;
  position: relative;
  #map {
    width: 100%;
  }
}

.refresh-station-box {
  position: fixed;
  z-index: 999;
  top: 161px;
  left: 8px;
  width: 36px;
  height: 36px;
  text-align: center;
  line-height: 36px;
  background: #fff;
  border: 1px solid #d9d9d9;
  color: #000;
  font-weight: 900;
}
::v-deep .ol-zoom-in,
::v-deep .ol-zoom-out {
  width: 36px;
  height: 36px;
}
</style>
